<template>
  <a-modal v-model:visible="visible" width="auto" footer="false">
    <template #title>文件管理</template>
    <div id="modal-content">
      <!-- 添加新建文件按钮 -->
      <a-space direction="vertical" style="margin-bottom: 16px; width: 100%">
        <a-button 
          type="primary" 
          @click="createFileModalVisible = true"
          style="width: 100%">
          <template #icon>
            <icon-plus />
          </template>
          新建文件
        </a-button>
      </a-space>

      <!-- 原有文件列表 -->
      <a-list>
        <a-list-item v-for="item in fileList" :key="item.id">
          <a-list-item-meta>
            <template #title>
              <a-tooltip :content="item.path">
                <span>{{ item.name }}</span>
              </a-tooltip>
            </template>
            <template #description>
              <span style="color: var(--color-text-3)">创建时间: {{ item.time }}</span>
            </template>
          </a-list-item-meta>
          <template #actions>
            <a-button type="text" @click="openFile(item.path, item.name)">打开文件</a-button>
            <a-button type="text" @click="deleteFile()">删除文件</a-button>
          </template>
        </a-list-item>
      </a-list>
    </div>
    <template #footer>
      <span style="color: var(--color-text-4)">Copyright 2025 Coconut Studio</span>
    </template>
  </a-modal>

  <a-modal v-model:visible="createFileModalVisible" title="新建文件" :footer="null">
    <a-space direction="vertical" size="large">
      <a-input v-model="newFileName" :style="{width:'320px'}" placeholder="请输入文件名" allow-clear>
        <template #suffix>
          <span>.boxy</span>
        </template>
      </a-input>
      <a-button type="primary" @click="createNewFile">新建文件</a-button>
    </a-space>
  </a-modal>
</template>

<script setup>
import { 
  IconPlus // 新增图标引入
} from '@arco-design/web-vue/es/icon'

import { ref, onMounted } from 'vue'
import Blockly from 'blockly'
import { useStore } from '../store/store'
import { Notification } from '@arco-design/web-vue';

const visible = ref(false)
const createFileModalVisible = ref(false)
const newFileName = ref('')
const fileList = ref([])
const store = useStore()

// 获取文件列表数据
async function fetchFileList() {
  try {
    const response = await fetch('/api/file_list')
    if (response.ok) {
      const data = await response.json()
      fileList.value = data.map((item, index) => ({
        id: index + 1,
        name: item.name,
        path: item.path,
        time: item.time
      }))
    } else {
      console.error('Failed to fetch file list:', response.status)
      Notification.error({
        title: '获取失败',
        content: response.json().error
      })
    }
  } catch (error) {
    console.error('Error fetching file list:', error)
    Notification.error({
      title: '获取失败',
      content: error
    })
  }
}

// 在组件挂载时获取文件列表
onMounted(fetchFileList)
onMounted(initializeFile)

async function initializeFile() {
  // 读取localStorage中的当前文件路径，并打开文件
  const currentFilePath = localStorage.getItem('currentFilePath')
  if (!currentFilePath) {
    // 如果没有找到当前文件路径，弹出新建文件模态框
    createFileModalVisible.value = true
  } else {
    const currentFileName = localStorage.getItem('currentFileName')
    openFile(currentFilePath, currentFileName)
  }
  // 读取localStorage中的currentProjectPath值，是否存在，如果不存在就在Cookie中获取
  const currentProjectPath = localStorage.getItem('currentProjectPath')
  if (!currentProjectPath) {
    const currentProjectPath = document.cookie.replace(/(?:(?:^|.*;\s*)currentProjectPath\s*\=\s*([^;]*).*$)|^.*$/, "$1")
    if (currentProjectPath) {
      localStorage.setItem('currentProjectPath', currentProjectPath)
    }
  }
}

function handleFilePanelClick() {
  visible.value = true
  fetchFileList()
}

async function openFile(path = '', name = '') {
  console.log(`Opening file at path: ${path}`)
  localStorage.setItem('currentFilePath', path)
  localStorage.setItem('currentFileName', name)
  document.cookie = `currentFilePath=${path};path=/`

  try {
    const response = await fetch('/api/get_file', {
      method: 'GET',
      headers: {
        'Content-Type': 'application/json'
      }
    })

    if (response.ok) {
      const data = await response.json()
      const fileContentBase64 = data.file_content
      const fileContent = atob(fileContentBase64)
      const json = JSON.parse(fileContent)
      Blockly.serialization.workspaces.load(json, store.workspaceSvg)
      visible.value = false
    } else {
      console.error('Failed to fetch file content:', response.status)
      Notification.error({
        title: '读取失败',
        content: '文件读取失败！'
      })
    }
  } catch (error) {
    console.error('Error fetching file content:', error)
    Notification.error({
      title: '读取失败',
      content: error
    })
  }
}

async function deleteFile() {
  try {
    const response = await fetch(`/api/delete_file`)
    if (response.ok) {
      Notification.success({
        title: '删除成功',
        content: '文件已删除'
      })
      await fetchFileList() // 刷新文件列表
    } else {
      Notification.error({
        title: '删除失败',
        content: `HTTP ${response.status} ${response.statusText}`
      })
    }
  } catch (error) {
    Notification.error({
      title: '删除失败',
      content: error.message
    })
  }
}

async function createNewFile() {
  const fileName = `${newFileName.value}.boxy`

  try {
    // 请求 /api/get_absolute_path 获取文件的绝对路径
    const response = await fetch(`/api/get_absolute_path?name=${fileName}`, {
      method: 'GET',
      headers: {
        'Content-Type': 'application/json'
      }
    })

    if (response.ok) {
      const data = await response.json()
      const absolutePath = data.absolute_path

      // 将绝对路径存储到 localStorage
      localStorage.setItem('currentFilePath', absolutePath)
      localStorage.setItem('currentFileName', fileName)

      // 调用 /api/save_file 保存文件
      const saveData = {
        path: absolutePath,
        content: btoa(JSON.stringify({})), // 空的 Blockly 工作区的 Base64 编码
        code: '' // 空的代码
      }

      const saveResponse = await fetch('/api/save_file', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json'
        },
        body: JSON.stringify(saveData)
      })

      if (saveResponse.ok) {
        Notification.success({
          title: '新建成功',
          content: '文件新建成功！'
        })
        createFileModalVisible.value = false
        newFileName.value = '' // 清空输入框
        fetchFileList() // 刷新文件列表
      } else {
        console.error('Failed to save file:', saveResponse.status)
        Notification.error({
          title: '新建失败',
          content: '文件保存失败！'
        })
      }
    } else {
      console.error('Failed to get absolute path:', response.status)
      Notification.error({
        title: '新建失败',
        content: '获取文件绝对路径失败！'
      })
    }
  } catch (error) {
    console.error('Error creating file:', error)
    Notification.error({
      title: '新建失败',
      content: error
    })
  }
}

defineExpose({ handleFilePanelClick, openFile })
</script>

<style>
#modal-content {
  -webkit-tap-highlight-color: transparent;
}
</style>